package com.duan.boot.exception;

import com.duan.boot.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * @author duan
 * @date 2022/11/9 20:30
 */
@ControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public R methodArgumentNotValidException(MethodArgumentNotValidException e){
        List<ObjectError> objectErrors =  e.getBindingResult().getAllErrors();
        List<String> resultErrors = new ArrayList<>();
        objectErrors.forEach(objectError -> {
            resultErrors.add(objectError.getDefaultMessage());
        });
        return R.fail(resultErrors);
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public R exceptionHandler(Exception e){
        return R.fail(e.getMessage());
    }
}
